package com.niiwoo.civet.account.service.local.openAccount2.listener;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.dao.entity.ActivityOrder;
import com.niiwoo.civet.account.dao.entity.OpenAccountRecord;
import com.niiwoo.civet.account.enums.OpenAccountRecordStatusEnum;
import com.niiwoo.civet.account.enums.OpenAccountWayEnum;
import com.niiwoo.civet.account.service.MarketingAsyncDubboService;
import com.niiwoo.civet.account.service.local.OldAccountBalanceService;
import com.niiwoo.civet.account.service.local.openAccount2.dto.OpenAccountEvent;
import com.niiwoo.tripod.lanmao.enums.UserRoleEnum;
import java.util.Arrays;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class OldBalanceListener implements OpenAccountListener {

    private static final List<OpenAccountWayEnum> INTERESTED_WAY_LIST = Arrays.asList(OpenAccountWayEnum.PERSON_BIND_BANK_CARD_REGISTER, OpenAccountWayEnum.R360_PERSON_BIND_BANK_CARD_REGISTER);

    private static final OpenAccountRecordStatusEnum EXCEPT_STATUS = OpenAccountRecordStatusEnum.SUCCESS;

    @Autowired
    OldAccountBalanceService oldAccountBalanceService;

    @Reference(version = "1.0.0")
    private MarketingAsyncDubboService marketingAsyncDubboService;

    @Override
    public void handle(OpenAccountEvent event) {
        OpenAccountRecord record = event.getRecord();
        ActivityOrder order = oldAccountBalanceService.prepare(record.getUserId(), record.getAccountNo(), UserRoleEnum.enumOf(record.getAccountRole()));
        if (order == null) {
            return;
        }
        log.info("开户成功###返还老账户余额###请求, order={}", JSON.toJSONString(order));
        try {
            marketingAsyncDubboService.sendPrize(order.getRequestNo(), UserRoleEnum.enumOf(order.getAccountRole()));
            log.info("开户成功###返还老账户余额###请求发送成功, userId={}, orderId={}", order.getUserId(), order.getId());
        } catch (Exception e) {
            log.error(String.format("开户成功###返还老账户余额###异常, userId=%s, orderId=%s, errorMessage=%s", order.getUserId(), order.getId(), e.getMessage()), e);
        }
    }

    @Override
    public boolean isExpectStatus(OpenAccountRecordStatusEnum status) {
        return EXCEPT_STATUS == status;
    }

    @Override
    public boolean isInterestedOpenAccountWay(OpenAccountWayEnum way) {
        return INTERESTED_WAY_LIST.contains(way);
    }
}
